// 选择文件
import common from './common.js'
const DownloadManager = plus.android.importClass('android.app.DownloadManager');
const Context = plus.android.importClass('android.content.Context');
const BroadcastReceiver = plus.android.importClass('android.content.BroadcastReceiver');
const IntentFilter = plus.android.importClass('android.content.IntentFilter');
const Intent = plus.android.importClass('android.content.Intent');
const MediaStore = plus.android.importClass('android.provider.MediaStore');
const MediaMetadataRetriever = plus.android.importClass('android.media.MediaMetadataRetriever');
const File = plus.android.importClass('java.io.File');
const FileWriter = plus.android.importClass('java.io.FileWriter');
const FileOutputStream = plus.android.importClass('java.io.FileOutputStream');
const Uri = plus.android.importClass('android.net.Uri');
const Bitmap = plus.android.importClass('android.graphics.Bitmap');
const sysInfo = uni.getSystemInfoSync();
const logPath = plus.io.convertLocalFileSystemURL('_doc/log.txt');

//获取视频信息
export function getVideoInfo(videoPath) {
	try {
		const media = new MediaMetadataRetriever();
		media.setDataSource(videoPath);
		const bitmap = media.getFrameAtTime();
		const thumbnail = plus.io.convertLocalFileSystemURL(`_doc/ChatFile/${common.guid()}.png`);
		const info = {
			width: bitmap.getWidth(),
			height: bitmap.getHeight(),
			duration: parseInt(media.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)) / 1000,
			thumbnail
		};
		const out = new FileOutputStream(new File(thumbnail));
		bitmap.compress(Bitmap.CompressFormat.JPEG, 10, out);
		media.release();
		out.flush();
		out.close();
		bitmap.recycle();
		return info;
	} catch (e) {
		console.log('缩略图获取失败', e);
	}
	return null;
}

// 记录日志
export function log(content = '') {
	try {
		// 打开一个写文件器，构造函数中的第二个参数true表示以追加形式写文件
		const writer = new FileWriter(logPath, true);
		content += ' ' + common.formatDate(new Date()) + '\n';
		writer.write(content);
		writer.flush();
		if (writer != null) {
			//关闭流
			writer.close();
		}
	} catch (e) {
		console.log(e);
	}
}

//下载APK
export function downloadAPK(versionUrl, versionName) {
	const main = plus.android.runtimeMainActivity();
	//创建下载任务
	let request = new DownloadManager.Request(Uri.parse(versionUrl));
	//在通知栏中显示
	request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
	request.setTitle(`${common.version.name}更新下载中...`);
	request.setVisibleInDownloadsUi(true);
	//保存目录
	const saveFolder = `_doc/Download/${versionName}`;
	const file = new File(plus.io.convertLocalFileSystemURL(saveFolder))
	request.setDestinationUri(Uri.fromFile(file));
	//将下载请求加入下载队列
	const downloadManager = main.getSystemService(Context.DOWNLOAD_SERVICE);
	downloadManager.enqueue(request);
	common.updating = true; //设置下载中
	const receiver = plus.android.implements("io.dcloud.android.content.BroadcastReceiver", {
		onReceive: (context, intent) => {
			common.updating = false;
			if (file.exists()) {
				common.execDelay(() => {
					plus.push.createMessage(`${common.version.name}最新版已下载完毕，请点击安装`, {
						type: 5, //安装类型
						filePath: file.getAbsolutePath()
					}, {
						title: common.version.name
					});
					uni.showConfirm({
						content: '最新版本已下载完毕，您是否现在安装？',
						confirmVal: '是',
						cancelVal: '否'
					}).then(() => {
						plus.runtime.install(file.getAbsolutePath());
					});
				}, 'DownloadAPK', 1000);
			}
		}
	});
	main.registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}

// 进入相机
export function enterCamera(callback) {
	plus.camera.getCamera(1).captureImage(
		filePath => {
			cropPhoto(Uri.parse(`file://${plus.io.convertLocalFileSystemURL(filePath)}`), callback);
		}, null, {
			filename: '_doc/camera/',
			optimize: false
		}
	);
}

//进入相册
export function enterGallery(callback) {
	const intent = new Intent(Intent.ACTION_PICK);
	intent.setDataAndType(MediaStore.Images.Media.INTERNAL_CONTENT_URI, "image/*");
	const main = plus.android.runtimeMainActivity();
	main.onActivityResult = (requestCode, resultCode, data) => {
		if (resultCode == -1) {
			cropPhoto(data.getData(), callback);
		}
	};
	main.startActivityForResult(intent, 1);
}

//裁剪照片
export function cropPhoto(uri, callback) {
	const IMAGE_UNSPECIFIED = 'image/*';
	const PHOTOZOOM = 2; // 获取完图片返回key
	const PHOTOLAT = 1; // 剪裁完毕后返回key
	const main = plus.android.runtimeMainActivity();
	const outRelativePath = `_doc/Avatar/${common.formatDate(new Date(),'yyyyMMddhhmmssS')}.jpg`; //返回的相对路径
	const outPutPath = plus.io.convertLocalFileSystemURL(outRelativePath);
	// 输出目录uri
	const outPutUri = Uri.fromFile(new File(outPutPath));
	const cropIntent = new Intent('com.android.camera.action.CROP');
	cropIntent.setDataAndType(uri, IMAGE_UNSPECIFIED);
	// 截图完毕后 输出目录
	cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, outPutUri);
	cropIntent.putExtra('crop', 'true');
	//华为会变圆形，特殊处理
	if (sysInfo.brand.includes("HUAWEI")) {
		cropIntent.putExtra("aspectX", 9998);
		cropIntent.putExtra("aspectY", 9999);
	} else {
		cropIntent.putExtra("aspectX", 1);
		cropIntent.putExtra("aspectY", 1);
	}
	// outputX outputY 是裁剪图片宽高
	cropIntent.putExtra('outputX', 390);
	cropIntent.putExtra('outputY', 390);
	cropIntent.putExtra('return-data', false);
	main.onActivityResult = (requestCode, resultCode, data) => {
		if (requestCode == PHOTOLAT && callback) {
			// 判断 剪裁完后的图片输出是否存在
			const file = new File(outPutPath);
			callback({
				success: file.exists(),
				filePath: outRelativePath
			});
		}
	};
	main.startActivityForResult(cropIntent, PHOTOLAT);
}

/**
 * 设置粘贴板数据
 * @param {String} text 要设置的字符串
 * 如果未设置参数，则清空数据
 */
export function setText(text) {
	try {
		var os = plus.os.name;
		text = text || '';
		if ('iOS' == os) {
			var pasteboard = plus.ios.invoke('UIPasteboard', 'generalPasteboard');
			plus.ios.invoke(pasteboard, 'setValue:forPasteboardType:', text, 'public.utf8-plain-text');
		} else {
			var main = plus.android.runtimeMainActivity();
			var clip = main.getSystemService('clipboard');
			plus.android.invoke(clip, 'setText', text);
		}
	} catch (e) {
		console.error('error @setClipboardText!!');
	}
}

//获取剪切板文字
export function getText() {
	try {
		var os = plus.os.name;
		if ('iOS' == os) {
			var pasteboard = plus.ios.invoke('UIPasteboard', 'generalPasteboard');
			return plus.ios.invoke(pasteboard, 'valueForPasteboardType:', 'public.utf8-plain-text')
		} else {
			var main = plus.android.runtimeMainActivity();
			var clip = main.getSystemService('clipboard');
			return plus.android.invoke(clip, 'getText');
		}
	} catch (e) {
		console.error('error @getClipboardText!!');
	}
}
